package org.example.controller;

import org.example.domain.*;
import org.example.service.ModuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author Jimmy
 * @version 1.0
 */
@Controller
@ResponseBody
public class ModuleController {

    @Autowired
    private ModuleService moduleService;

    /**
     * 分页查询
     * @param pagenum 当前页数
     * @param pagesize 每页显示条目数
     * @return json
     */
    @GetMapping(value = "/models")
    public JsonData<PageBean<Model>> pageBean(@RequestParam(required = false) String modelId,@RequestParam(required = false) String modelName,@RequestParam(required = false) String pName,int pagenum,int pagesize){
        PageBean<Model> pageBean = moduleService.findByPage(new Model(modelId,modelName,pName),pagenum, pagesize);
        Meta meta;
        if (pageBean != null){
            meta = new Meta("获取成功",200);
        }else {
            meta = new Meta("获取失败",404);
        }
        return new JsonData<>(pageBean,meta);
    }

    /**
     * 添加模块信息
     * @param model model
     * @return json
     */
    @PostMapping(value = "/addModel")
    public JsonData<String> addModule(@RequestBody Model model){
        Meta meta;
        int i = moduleService.addModule(model);
        if (i != 0){
            meta = new Meta("添加成功",200);
        }else {
            meta = new Meta("添加失败",500);
        }
        return new JsonData<>(meta);
    }

    /**
     * 根据id获取模块信息
     * @param modelId
     * @return
     */
    @GetMapping(value = "/getModel/{modelId}")
    public JsonData<Model> findOneById(@PathVariable(value = "modelId") String modelId){
        Meta meta;
        Model model = moduleService.findById(modelId);
        if (model != null){
            meta = new Meta("获取成功",200);
        }else {
            meta = new Meta("获取失败",404);
        }
        return new JsonData<>(model,meta);
    }

    /**
     * 修改模块信息
     * @param model model
     * @return json
     */
    @PutMapping(value = "/updateModel/{modelId}")
    public JsonData<String> update(@PathVariable(value = "modelId")String modelId,@RequestBody(required = false) Model model){
        model.setModelId(modelId);
        int i = moduleService.update(model);
        Meta meta;
        if (i != 0){
            meta = new Meta("修改成功",200);
        }else {
            meta = new Meta("修改失败",404);
        }
        return new JsonData<>(meta);
    }

    /**
     * 删除模块信息
     * @param modelId 模块id
     * @return json
     */
    @DeleteMapping(value = "/deleteModel/{modelId}")
    public JsonData<String> delete(@PathVariable(value = "modelId") String modelId){
        int i = moduleService.delete(modelId);
        Meta meta;
        if (i != 0){
            meta = new Meta("删除成功",200);
        }else {
            meta = new Meta("删除失败",404);
        }

        return new JsonData<>(meta);
    }


}
